package com.kuang.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Administrator
 * @date 2021/5/28 16:34
 * Description:
 */
public class TestSpinLock {
    public static void main(String[] args) throws InterruptedException {
        //之前用的锁
//        ReentrantLock reentrantLock = new ReentrantLock();
//        reentrantLock.lock();
//        reentrantLock.unlock();

        //自己定义的锁
        SpinLockDemo lock = new SpinLockDemo();
        new Thread(()->{
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(2);
            }catch (Exception e) {
                e.printStackTrace();
            }finally {
                lock.myUnlock();
            }
        }, "T1").start();

        TimeUnit.SECONDS.sleep(1);

        new Thread(()->{
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(1);
            }catch (Exception e) {
                e.printStackTrace();
            }finally {
                lock.myUnlock();
            }
        }, "T2").start();
        //整个过程中 T1在休眠 T2在自旋 等待T1解锁后T2才能解锁
    }
}
